package io.xiaojl.xj2ee.ds.aspect;

import java.lang.reflect.Method;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;

import io.xiaojl.xj2ee.ds.DataSourceNames;
import io.xiaojl.xj2ee.ds.DynamicDataSource;
import io.xiaojl.xj2ee.ds.annotation.XjeeDataSource;

/**
 * 
 * <p>Title: DataSourceAspect</p>  
 *
 * <p>Description: 多数据源，切面处理类</p>  
 *
 * @author jilong.xiao  
 * @date 2018年5月28日
 */
@Aspect
@Component
public class DataSourceAspect implements Ordered {
    protected Logger logger = LoggerFactory.getLogger(getClass());

    @Pointcut("@annotation(io.xiaojl.xj2ee.ds.annotation.XjeeDataSource)")
    public void dataSourcePointCut() {

    }

    @Around("dataSourcePointCut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        MethodSignature signature = (MethodSignature) point.getSignature();
        Method method = signature.getMethod();

        XjeeDataSource ds = method.getAnnotation(XjeeDataSource.class);
        String dsName = DataSourceNames.FIRST;
        if(ds != null){
        	dsName = ds.name();
        }
        logger.debug("使用的数据源：" + dsName);
        DynamicDataSource.setDataSource(dsName);

        try {
            return point.proceed();
        } finally {
            DynamicDataSource.clearDataSource();
            logger.debug("clean datasource");
        }
    }

    @Override
    public int getOrder() {
        return 1;
    }
}
